package chen.web.email;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SMTPSender implements EmailSender {

	private String smtpHost = null;			//smtp服务器域名
	private String username = null;		//用户名
	private String password = null;		//密码
	private EmailAddress senderAddress = null;		//发件人邮箱地址
	
	private static Log log = LogFactory.getLog(SMTPSender.class);
	
	public SMTPSender(EmailAddress senderAddress, String smtpHost, String username, String password){
		this.senderAddress = senderAddress;
		this.smtpHost = smtpHost;
		this.username = username;
		this.password = password;
	}
	
	@Override
	public boolean send(SimpleEmail email) {
		// TODO Auto-generated method stub
		try{
			if(log.isDebugEnabled()){
				log.debug("发送邮件到:" + email.getTo());
			}
			JavaMailSenderImpl sender = new JavaMailSenderImpl();
			sender.setHost(smtpHost);
			sender.setUsername(username);	
			sender.setPassword(password);	
			sender.setDefaultEncoding("UTF-8");	//设置编码
			
			MimeMessage message = sender.createMimeMessage();
			MimeMessageHelper helper = null;
			List<File> attachments = email.getAttachments();
			if(attachments != null && attachments.size() != 0){
				helper = new MimeMessageHelper(message, true, "UTF-8");
				for(File attachment : attachments){
					String name = "unkown";
					try {
						//添加附件，对附件名编码
						name = MimeUtility.encodeWord(attachment.getName());
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						log.error("对邮件附件名编码时发生错误,附件名:" + attachment.getName(), e);
					}
					helper.addAttachment(name, attachment);
				}
			} else {
				helper = new MimeMessageHelper(message, false, "UTF-8");
			}
			
			helper.setFrom(senderAddress.encode());
			helper.setTo(email.getTo().encode());
			helper.setText(email.getHtml(), true);
			helper.setSubject(email.getSubject());
			sender.send(message);
		}catch(Exception ex){
			log.error("发送email出错，地址：" + email.getTo().getAddress(), ex);
			return false;
		}
		return true;
	}

}
